#!/usr/bin/env python

import optparse
import os

import tables

from charmicat import BadCommandLineError

import ypipi

default_kwargs = {'xlim': (9,10.6), 
                  'ylim': (9,10.6), 
                  'xlabel': r'MM($\pi^0\pi^0$)', 
                  'ylabel': r'M($\mu^+\mu^-$)', 
                  'title': r'Even More Permissive GammaList', 
                  'out': 'test.png'
                  }

def main():
    '''
    ypipi_scatter.py file.h5 [kwarg=value [kwarg=value [...]]
    
    Produce the scatterplot of MM(pi0pi0) vs M(mumu)
    '''

    op = optparse.OptionParser(usage=main.__doc__)

    opts, args = op.parse_args()

    if len(args) == 0:
        raise BadCommandLineError("Please supply a PyTables file as input", -1)

    with tables.openFile(args[0]) as fp:
        if 'mm_off_pi0pi0' in fp.root.nt.colnames:
            x = fp.root.nt[:]['mm_off_pi0pi0']
            y = fp.root.nt[:]['m_mumu']
        else:
            x = fp.root.nt[:]['recm2pi']
            y = fp.root.nt[:]['m2mu']

    kwargs = {}
    kwargs.update(default_kwargs)

    kwargs['out'] = os.path.basename(args[0]).rsplit('.', 1)[0] + '.png'
    kwargs['title'] = os.path.basename(args[0])

    kwargs.update(dict([kwarg.split('=') for kwarg in args[1:]]))

    ypipi.scatter(x, y, **kwargs)

    return 0


if __name__ == "__main__":
    try:
        import sys
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)


